package net.lwf.jaxb.util;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class XmlFileInfo {
	private String baseName;
	private String fullName;
	private String jarName;
	
	private long xmlFileTimestamp = -1;
	
	public XmlFileInfo(String fileName) {
		super();
		baseName = fileName;
		determineFileInfo();
	}
	
	private void determineFileInfo() {
		fullName = null;
		
		try {
			URL url = Thread.currentThread().getContextClassLoader().getResource(baseName);
			if (url != null) {
				fullName = url.getFile();
				int jarIdx = fullName.indexOf("!/" + baseName);
				if (jarIdx > -1) {
					jarName = fullName.substring(0, jarIdx);
					if (jarName.startsWith("file:")) {
						jarName = jarName.substring(5);
					}
					JarFile jarFile = new JarFile(jarName);
					JarEntry jarEntry = jarFile.getJarEntry(baseName);
					xmlFileTimestamp = jarEntry.getTime();
					jarFile.close();
				} else {
					File xmlFile = new File(fullName);
					xmlFileTimestamp = xmlFile.lastModified();
				}
			}
		} catch (Exception exc) {
			throw new IllegalArgumentException ("Error processing file:" + baseName + " with a full name of " + fullName);
		}
	}
	
	public boolean isChanged() {
		
		long lastTimestamp = xmlFileTimestamp;
		
		determineFileInfo();
		
		return (lastTimestamp != xmlFileTimestamp);
	}
	
	public InputStream getInputStream() {
		return Thread.currentThread().getContextClassLoader().getResourceAsStream(baseName);
	}
}
